//当前激活tab
var activeTab = "main";

//agentId，保留，当前未使用，默认为""
var agentId = "";
//userId
var userId = "";

//各功能聊天室对话框
var voipMsgWindow = null;

// 集成文档请参考 https://docs.starrtc.com/en/docs/web-7.html

var aecRequestBaseURL = "https://www.starrtc.com/aec";				//开启AEC后，才生效，从此url获取各种列表信息
var privateURL = "192.168.1.7";								//后端服务地址，可为ip，也可为域名
var webrtcIP = "192.168.1.7";										//后端服务地址，必须为ip（目前只有chrome72以上支持设置成域名），webrtc ip，用于设置webrtc udp ip，用于setSrcServerInfo，setVdnServerInfo，setVoipServerInfo接口，不设置时与后端服务地址privateURL一致


/* var LOG_LEVEL = {
	LOG_LEVEL_DEBUG: i++,
	LOG_LEVEL_INFO: i++,
	LOG_LEVEL_WARN: i++,
	LOG_LEVEL_ERROR: i++ */

//设置日志等级，开启低等级日志会包含高等级日志，如开启DEBUG，则同时开启INFO、WARN、ERROR，默认为开启DEBUG
StarRtc.InitlogLevel(LOG_LEVEL.LOG_LEVEL_INFO);

//创建SDK对象
StarRtc.Instance = new StarRtc.StarSDK();

////////////////////////私有云改配置///////////////////////
///////////////////////以下privateURL需替换为私有部署IP////

//StarRtc.Instance.setConfigUseAEC(true);    							//是否开启AEC

StarRtc.Instance.setMsgServerInfo(privateURL, 19903) 					//ip, websocket port  //需要手动从浏览器输入 https://ip:29991 信任证书

StarRtc.Instance.setChatRoomServerInfo(privateURL, 19906) 			//ip, websocket port //需要手动从浏览器输入 https://ip:29993 信任证书

StarRtc.Instance.setSrcServerInfo(privateURL, 19934, 19935, webrtcIP)  			//ip, websocket port, webrtc port, webrtc ip//需要手动从浏览器输入 https://ip:29994 信任证书

StarRtc.Instance.setVdnServerInfo(privateURL, 19940, 19941, webrtcIP) 			//ip, websocket port, webrtc port, webrtc ip //需要手动从浏览器输入 https://ip:29995 信任证书

StarRtc.Instance.setVoipServerInfo(privateURL, 10086, 10087, 10088, webrtcIP) 	//ip, voipServer port, websocket port, webrtc port, webrtc ip //需要手动从浏览器输入 https://ip:29992 信任证书


//白板画布类
var MyCanvas = function (_id, _draw_mode, _draw_callback) {
    var id = _id;
    var draw_mode = false || _draw_mode;
    var draw_callback = null || _draw_callback;
    var canvasObj = $("#" + id);
    if (canvasObj == undefined) {
        return null;
    }
    var ctx = canvasObj[0].getContext('2d');
    ctx.fillStyle = 'rgba(255, 255, 255, 0)';

    var drawPoints = [];
    var points = {};
    points["-1"] = [];

    if (draw_mode) {
        canvasObj.unbind("mousedown");
        canvasObj.unbind("mousemove");
        canvasObj.unbind("mouseup");

        canvasObj.bind("mousedown", function (ev) {
            var ev = ev || window.event;

            ctx.strokeStyle = "red";
            ctx.lineCap = 'round';
            ctx.lineWidth = 4;

            drawPoints = [];

            ctx.beginPath();
            ctx.moveTo(ev.offsetX, ev.offsetY);
            drawPoints.push([ev.offsetX, ev.offsetY]);
            canvasObj.bind("mousemove", function (ev) {
                var ev = ev || window.event;
                ctx.lineTo(ev.offsetX, ev.offsetY);
                drawPoints.push([ev.offsetX, ev.offsetY]);
                ctx.stroke();
            });
        });

        canvasObj.bind("mouseup", function (ev) {
            canvasObj.unbind("mousemove");
            drawPoints.push([0, 0]);
            if (draw_callback != null) {
                draw_callback(drawPoints);
            }
            points["-1"] = points["-1"].concat(drawPoints);
        });
    }

    MyCanvas.prototype.addPoint = function (_id, x, y) {
        if (points[_id] == undefined) {
            points[_id] = [];
        }
        points[_id].push([x, y]);
    }

    MyCanvas.prototype.setSize = function (width, height) {
        canvasObj[0].width = width;
        canvasObj[0].height = height;
        ctx = canvasObj[0].getContext('2d');
        ctx.fillStyle = 'rgba(255, 255, 255, 0)';
    }

    MyCanvas.prototype.fitSize = function () {
        if (canvasObj[0].width != canvasObj[0].clientWidth || canvasObj[0].height != canvasObj[0].clientHeight) {
            this.setSize(canvasObj[0].clientWidth, canvasObj[0].clientHeight);
        }
    }

    MyCanvas.prototype.redraw = function () {
        this.fitSize();
        this.clearCanvas();
        for (var upId in points) {
            var count = 0;
            if ((count = points[upId].length) > 1) {
                var selectColor = "red";
                switch (upId) {
                    case "-1":
                        selectColor = "#FF6c00";
                        break;
                    case "0":
                        selectColor = "#FF4081";
                        break;
                    case "1":
                        selectColor = "yellow";
                        break;
                    case "2":
                        selectColor = "blue";
                        break;
                    case "3":
                        selectColor = "cyan";
                        break;
                    case "4":
                        selectColor = "green";
                        break;
                    case "5":
                        selectColor = "magenta";
                        break;
                    case "6":
                        selectColor = "red";
                        break;
                }

                ctx.lineCap = 'round';
                ctx.lineWidth = 4;
                ctx.strokeStyle = selectColor;

                var flag = false;
                var linePoints = 0;

                for (var i = 0; i < count; ++i) {
                    if (!flag) {
                        ctx.beginPath();
                        ctx.moveTo(points[upId][i][0], points[upId][i][1]);
                        flag = true;
                        linePoints = 1;
                    }
                    else {
                        if (points[upId][i][0] <= 0) {
                            if (linePoints > 1) {
                                ctx.stroke();
                            }
                            flag = false;
                        }
                        else {
                            ctx.lineTo(points[upId][i][0], points[upId][i][1]);
                            linePoints++;
                        }
                    }
                }
                if (flag && linePoints > 1) {
                    ctx.stroke();
                }
            }
        }
    }

    MyCanvas.prototype.clearCanvas = function () {
        ctx.clearRect(0, 0, canvasObj[0].width, canvasObj[0].height);
    }

    MyCanvas.prototype.clearAll = function () {
        points = { "-1": [] };
        this.clearCanvas();
    }

    return this;
}

//点击返回触发的函数
var currFunc = {
    "exit": undefined
};

//登陆成功后界面设置
function loginSuccessViewSet() {
    switchLogin(false);
    $("#userId").html(userId);
    $("#userImage").html("<image src=\"images/user.png\" />");
    bindTabs(true);
    voipMsgWindow.userName = userId;
    voipMsgWindow.setShowHideCallBack(1000, null, 1000, function () {
        $("#voipVideoZone").css("width", "100%");
        $("#voipMessageButton").show();
    });
}

//注销
function starlogout() {
    StarRtc.Instance.logout();
    bindTabs(false);
    $("#userImage").html("");
    userId = "";
    $("#userId").html("请先登录");
    switchLogin(true);
}

function switchLogin(flag) {
    $("#login").unbind("click");
    $("#login").bind("click", flag ? starlogin : starlogout);
    $("#login").html(flag ? "登录" : "退出");
}

function showMainTab() {
    activeTab = "main";
    $(".tab[id!=mainTab]").hide();
    $("#mainTab").slideDown(2000);
}

function showVoipTab() {
    activeTab = "voip";
    $(".tab").hide();
    $("#voipTab").slideDown(2000, enterVoipFunc);
}

function bindTabs(flag) {
    if (flag) {
        $("#voipButton").bind("click", showVoipTab);
    }
    else {
        $("#voipButton").unbind("click");
    }
}

function bindEvent() {
    $(".backButton").each(function (id, ele) {
        $(ele).bind("click", function () {
            showMainTab();
            if (currFunc.exit != undefined) {
                currFunc.exit();
            }
        });
    });

    $("#voipMessageButton").bind("click", function () {
        $("#voipVideoZone").css("width", "85%");
        $("#voipVideoZone").css("float", "left");
        $("#voipMessageButton").hide();
        voipMsgWindow.show();
    });

    $("#voipCalling").bind("click", openCallDlg);
    $("#voipHangup").bind("click", hangupVOIP);

    //$("#voipSmallVideo").bind("click", switchVoipVideo);
    //$("#voipBigVideo").bind("click", switchVoipVideo);

}
//////////////////////////////////////////////star box////////////////////////////////////////
function starlogin(evt, _userId) {
    //userId随机生成，类型为字符串
    if (_userId == undefined) {
        _userId = "" + (Math.floor(Math.random() * 899999) + 100000);
    }
    userId = _userId;
    $("#userImage").html("<div class=\"rect1\"></div>\n<div class=\"rect2\"></div>\n<div class=\"rect3\"></div>\n<div class=\"rect4\"></div>\n<div class=\"rect5\"></div>");
    setCookie("starrtc_userId", userId, null);
    //登录
    starRtcLogin(agentId, userId, starRtcLoginCallBack);
}

//登录时传入的回调函数，IM，群组，系统消息在此回调中处理
function starRtcLoginCallBack(data, status) {
    switch (status) {
        //链接状态
        case "connect success":
            break;
        case "connect failed":
            alert("登录连接失败!");
            break;
        case "connect closed":
            break;
        //收到登录消息
        case "onLoginMessage":
            if (data.status == "success") {
                loginSuccessViewSet();
            }
            console.log("login:" + data.status);
            break;
        //收到IM消息
        case "onSingleMessage":
            var fid = data.fromId;
            voipMsgWindow.displayMessage(data.fromId, data.msg.contentData, false);
            break;
        //收到群组消息
        case "onGroupMessage":
            break;
        //收到群组私聊消息
        case "onGroupPrivateMessage":
            break;
        //收到群组推送消息
        case "onGroupPushMessage":
            break;
        //收到系统推送消息
        case "onSystemPushMessage":
            break;
        //收到voip消息
        case "onVoipMessage":
            switch (data.type) {
                //收到voip视频呼叫消息
                case "voipCall":
                    $("#callerId").html(data.fromId);
                    $("#callerType").html("视频");
                    voipAudio = false;
                    voipResponseDlg.dialog("open");
                    break;
                //收到voip音频呼叫消息
                case "voipAudioCall":
                    $("#callerId").html(data.fromId);
                    $("#callerType").html("音频");
                    voipAudio = true;
                    voipResponseDlg.dialog("open");
                    break;
                //收到voip挂断消息
                case "voipHangup":
                    voipResponseDlg.dialog("close");
                    break;
                //收到voip拒绝消息
                case "voipRefuse":
                    voipConnectDlg.dialog("close");
                    $("#callerId").html("");
                    alert("对方拒绝了通话！");
                    break;
            }
            break;
        //收到错误消息
        case "onErrorMessage":
            switch (data.errId) {
                //收到重复登录消息
                case 2:
                    alert("您的账号在另外的设备登录，您已经下线");
                    $(".backButton")[0].click();
                    starlogout();
                    break;
            }
            break;
        //收到群组列表回调（仅非AEC）
        case "onGetGroupList":
            break;
        //收到在线人数回调
        case "onGetOnlineNumber":
            break;
        //收到推送群组成员回调（仅非AEC）
        case "onGetGroupUserList":
            break;
        //收到推送群组系统消息回调
        case "onGetAllUserList":
            break;
        //收到推送群组系统消息回调
        case "onPushGroupSystemMsgFin":
            break;
        //收到推送系统消息回调
        case "onPushSystemMsgFin":
            break;
        //收到取消免打扰回调（仅非AEC）
        case "onUnsetGroupMsgIgnoreFin":
            break;
        //收到设置免打扰回调（仅非AEC）
        case "onSetGroupMsgIgnoreFin":
            break;
        //收到移除群组成员回调
        case "onRemoveGroupUserFin":
            break;
        //收到添加群组成员回调
        case "onAddGroupUserFin":
            break;
        //收到删除群组回调
        case "onDelGroupFin":
            break;
        //收到创建群组回调
        case "onCreateGroupFin":
            break;
        //收到发送群组消息回调
        case "onSendGroupMsgFin":
            break;
    }
};

//登录函数
function starRtcLogin(agentId, userId, callBack) {
    //获取SDK版本
    StarRtc.Instance.version();
    //SDK登录函数
    StarRtc.Instance.login(agentId, userId, callBack);
}
//////////////////////////////////////////////star box end////////////////////////////////////////
//////////////////////////////////////////////voip////////////////////////////////////////////
var currRoom = null;

var voipResponseDlg;
var voipConnectDlg;
var voipCallDlg;
//voip 仅音频标志位
var voipAudio = true;

function enterVoipFunc() {
    console.info('enterVoipFunc');
    currFunc.exit = exitVoipFunc;
}

//退出voip
function exitVoipFunc() {
    console.info('exitVoipFunc');
    if (currRoom != null) {
        currRoom.leaveRoom();
        currRoom.sigDisconnect();
        currRoom = null;
    }
}

//打开voip呼叫页面
function openCallDlg() {
    console.info('openCallDlg');	
    var targetUid = $('#targetUserId').val().trim();
    if (targetUid == null || targetUid == undefined || targetUid == "") {
        alert("对方ID不能为空");
        return;
    }
    $("#calleeId").html(targetUid);
    voipCallDlg.dialog("open");
}

//开始voip呼叫
function callingVOIP() {
    console.info('callingVOIP');	
    var targetUid = $('#targetUserId').val().trim();
    if (targetUid == null || targetUid == undefined || targetUid == "") {
        alert("对方ID不能为空");
        return;
    }
    voipCallDlg.dialog("close");

    voipAudio = $('#voipTypeAudioOnly').is(':checked');

    //获取voipSDK
    currRoom = StarRtc.Instance.getVoipRoomSDK("call", voipCallBack, { "roomInfo": { "targetId": targetUid, "audioOnly": voipAudio } });
    //链接
    currRoom.sigConnect();
    console.info('connecting...');	
    voipConnectDlg.dialog("open");
}

//挂断voip
function hangupVOIP() {
    console.info('hangupVOIP');	
    exitVoipFunc();
}

//voip回调函数
function voipCallBack(data, status, oper) {
    var thisRoom = data.obj;
    switch (status) {
        //链接状态
        case "connect success":
            //创建视频流，会触发onWebrtcMessage中的streamCreated回调
	    console.info('voipCallBack status connect success');
            thisRoom.createStream();
            break;
        case "connect failed":
        case "connect closed":
	    console.info('voipCallBack status connect failed or closed');	    
            stopVoip();
            break;
        //收到视频相关回调
        case "onWebrtcMessage":
	    console.info('voipCallBack status onWebrtcMessage data.type is '+data.type);	    
            switch (data.type) {
                //收到流创建回调
                case "streamCreated":
		    console.info('voipCallBack status onWebrtcMessage data.type is streamCreated');
		    console.info(data);
                    if (data.status == "success") {
                        // voipSetStream($("#voipSmallVideo")[0], data.streamObj);
                        //加入房间
                        thisRoom.joinRoom();
                    }
                    else {
                        voipConnectDlg.dialog("close");
                        alert("获取摄像头视频失败！请检查摄像头设备是否接入！error:" + data.error);
                    }
                    break;
                //收到voip 呼叫回调
                case "voipCalling":
                    if (data.status == "success") {
                        //服务端录屏session id
                        console.log("recSessionId:" + data.recSessionId);
                    }
                    break;
                //收到voip 应答回调
                case "voipResponseing":
                    if (data.status == "success") {
                        //服务端录屏session id
                        console.log("recSessionId:" + data.recSessionId);
                        $('#targetUserId').val(data.userData.roomInfo.targetId);
                    }
                    break;
                //收到voip 通话成功后，获取到对方视频流
                case "voipStreamReady":
		    console.info('voipCallBack status onWebrtcMessage data.type is voipStreamReady');
		    console.info(data);	
                    if (data.userData.roomInfo.audioOnly) {
                        voipSetStream($("#voipBigAudio")[0], data.streamObj);
                    }
                    else {
			//voipSetStream($("#voipSmallVideo")[0], data.streamObj);    
                        voipSetStream($("#voipBigVideo")[0], data.streamObj);
                    }
                    break;
            }
            break;
        //收到voip IM 消息
        case "onVoipMessage":
            switch (data.type) {
                //收到voip 拒绝通话
                case "voipRefuse":
                    voipConnectDlg.dialog("close");
                    $("#callerId").html("");
                    alert("对方拒绝了通话！");
                    thisRoom.sigDisconnect();
                    break;
                //收到voip 挂断通话
                case "voipHangup":
                    alert("对方挂断了通话！");
                    thisRoom.sigDisconnect();
                    break;
                //收到voip 通话链接
                case "voipConnect":
                    voipConnectDlg.dialog("close");
                    break;
                //收到voip 对方忙碌
                case "voipBusy":
                    alert("对方正忙！");
                    thisRoom.sigDisconnect();
                    break;
                //收到voip IM 聊天消息
                case "voipSingleMsg":
                    voipMsgWindow.displayMessage(data.fromId, data.msg.contentData, false);
                    break;
            }
            break;
    }
}

function voipSetStream(videoObj, streamObj) {
    console.info('play stream in '+videoObj.id);	
    videoObj.srcObject = streamObj;
    videoObj.play();
}

var voipMode = true;
/*
function switchVoipVideo() {
    console.info('swithVoipVideo');	
    $("#voipSmallVideo")[0].style = "float:left;";
    $("#voipBigVideo")[0].style = "";
    if (voipMode) {
        $("#voipSmallVideo").animate({ "max-width": "85%", "height": "100%" }, 1000);
        $("#voipBigVideo").animate({ "width": "15%", "max-height": "100%" }, 1000);
    }
    else {
        $("#voipBigVideo").animate({ "max-width": "85%", "height": "100%" }, 1000);
        $("#voipSmallVideo").animate({ "width": "15%", "max-height": "100%" }, 1000);
    }
    voipMode = !voipMode;
}
*/
//voip 同意接受对方呼叫
function voipAcceptCall() {
    console.info('voipAcceptCall');	
    if (currFunc.exit != undefined) {
        currFunc.exit();
    }
    showVoipTab();

    var targetId = $("#callerId").html();
    //获取voipSDK
    currRoom = StarRtc.Instance.getVoipRoomSDK("response", voipCallBack, { "roomInfo": { "targetId": targetId, "audioOnly": voipAudio } });
    //链接
    currRoom.sigConnect();
    voipResponseDlg.dialog("close");
}

//voip 拒绝接受对方呼叫
function voipRefuseCall() {
    console.info('voopRefuseCall');	
    var targetId = $("#callerId").html();
    StarRtc.Instance.sendVoipRefuseMsg(targetId);
    voipResponseDlg.dialog("close");
}

//voip 取消呼叫
function voipCancleCall() {
    console.info('voipCancelCall'); 	
    hangupVOIP();
    voipConnectDlg.dialog("close");
}

//停止voip
function stopVoip() {
    console.info('stopVoip');
    currRoom = null;
    voipResponseDlg.dialog("close");
    voipConnectDlg.dialog("close");
    voipCallDlg.dialog("close");
    $("#callerId").html("");
    $('#targetUserId').val("");
    $("#voipBigVideo")[0].srcObject = null;
  //  $("#voipSmallVideo")[0].srcObject = null;
}

//voip 发送消息
function voipInputMsgCallBack(msg) {
    console.info('voipInputMsgCallBack'+msg);	
    if (currRoom != null) {
        currRoom.sendVoipMsg(msg);
    }
}

//////////////////////////////////////////////void end////////////////////////////////////////

$().ready(function () {

    showMainTab();

    var fullHeight = $($(".tab")[0]).height();
    var fullWidth = $($(".tab")[0]).width();
    var backButtonHeight = $($(".backButton")[0]).height() + 20;

    $("#voipCtrl").height(fullHeight - backButtonHeight);
    $("#voipZone").height(fullHeight - backButtonHeight);

    voipMsgWindow = new MyMsgWindow("voipMsgWindow", voipInputMsgCallBack);

    $("#voipMsgWindow").hide();

    voipResponseDlg = $("#voipResponseDlg").dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "同意": voipAcceptCall,
            "拒绝": voipRefuseCall
        },
        open: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        },
    });

    voipConnectDlg = $("#voipConnectDlg").dialog({
        autoOpen: false,
        height: 220,
        width: 300,
        modal: true,
        buttons: {
            "取消呼叫": voipCancleCall
        },
        open: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        },
    });

    voipCallDlg = $("#voipCallDlg").dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "确定": callingVOIP,
            "取消": function () {
                voipCallDlg.dialog("close");
            }
        }
    });

    $("#voipTypeAudioOnly").checkboxradio();

    var localId = getCookie("starrtc_userId");
    if (localId != "") {
        userId = localId;
        starRtcLogin(agentId, userId, starRtcLoginCallBack);
    }
    else {
        switchLogin(true);
    }

    bindEvent();

    $("#sdkVersion").html(StarRtc.Instance.version());
});
